package com.kh.pajx.sop.view.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.kh.pajx.sop.base.ModelDrivenBaseAction;
import com.kh.pajx.sop.base.SOPConfig;
import com.kh.pajx.sop.domain.HsSchoolInfo;
import com.kh.pajx.sop.domain.SysDictionary;
import com.kh.pajx.sop.domain.SysMenuAuth;
import com.kh.pajx.sop.domain.SysUserGroup;
import com.kh.pajx.sop.domain.SysUserRole;
import com.kh.pajx.sop.util.common.DwzAjaxResult;
import com.kh.pajx.sop.util.common.ValidatorUtils;
import com.kh.pajx.sop.util.page.QueryHelper;
import com.kh.pajx.sop.util.sop.PropertyValidate;
import com.opensymphony.xwork2.ActionContext;

/**
 * 用户组角色Struts2逻辑控制器
 * @author:	azzcsimp
 * @Createdate:	2014年7月18日 下午3:39:09
 */
@Controller
@Scope("prototype")
public class SysUserRoleAction extends ModelDrivenBaseAction<SysUserRole> {

	private static final long serialVersionUID = 8080729944319631950L;
	
	/** 用户组编号 */
	private String usgId;
	
	/** 用户组编码 */
	private String usgCode;
	
	/** 选中菜单集合 */
	private String menuIds;

	/** 列表 */
	public String list() {
		new QueryHelper(SysUserRole.class, "usr").addOrderProperty(
				"usr.usrCode", true).preparePageBean(sysUserRoleService,
				pageNum, numPerPage);
		return "list";
	}

	/** 添加页面 */
	public String addUI() {
		// 准备数据
		List<SysUserGroup> userGroupList = sysUserGroupService.findAll();
		ActionContext.getContext().put("userGroupList", userGroupList);
		return "saveUI";
	}

	/** 添加 */
	public void add() {
		DwzAjaxResult dwz = new DwzAjaxResult();
		try {
			validatePropertitysByAdd(model);//数据安全验证
			SysUserGroup userGroup = sysUserGroupService.getById(usgId);
			model.setUsrCode(sysUserRoleService.getUsrCode(userGroup
					.getUsgCode()));
			model.setSysUserGroup(userGroup);
			sysUserRoleService.save(model);
			dwz.setMessage("保存成功！");
			dwz.setNavTabId("userRole_list");
			dwz.setStatusCode("200");
			dwz.setCloseDialog("userRole_addUI");
			DwzAjaxResult.josnMessage(dwz);
		} catch (Exception e) {
			e.printStackTrace();
			dwz.setMessage("保存失败！<br>错误信息：" + e.getMessage());
			dwz.setStatusCode("300");
			DwzAjaxResult.josnMessage(dwz);
		}
	}

	/** 修改页面 */
	public String editUI() {
		// 准备数据
		List<SysUserGroup> userGroupList = sysUserGroupService.findAll();
		ActionContext.getContext().put("userGroupList", userGroupList);

		SysUserRole userRole = sysUserRoleService.getById(model.getUsrId());
		ActionContext.getContext().getValueStack().push(userRole);
		return "saveUI";
	}

	/** 修改 */
	public void edit() {
		DwzAjaxResult dwz = new DwzAjaxResult();
		try {
			validatePropertitysByUpdate(model);//安全验证
			SysUserRole userRole = sysUserRoleService.getById(model.getUsrId());
			userRole.setUsrName(model.getUsrName());
			userRole.setUsrDataRange(model.getUsrDataRange());
			
			sysUserRoleService.update(userRole);
			dwz.setMessage("修改成功!");
			dwz.setNavTabId("userRole_list");
			dwz.setStatusCode("200");
			dwz.setCloseDialog("userRole_editUI");
			DwzAjaxResult.josnMessage(dwz);
		} catch (Exception e) {
			e.printStackTrace();
			dwz.setMessage("修改失败！<br>错误信息：" + e.getMessage());
			dwz.setStatusCode("300");
			DwzAjaxResult.josnMessage(dwz);
		}
	}

	/** 删除 */
	public void delete() {
		DwzAjaxResult dwz = new DwzAjaxResult();
		try {
			validatePropertitysByDel(model);//安全验证
			SysUserRole userRole = sysUserRoleService.getById(model.getUsrId());
			
			// ==>1.判断是否包含菜单权限控制
			if(null!=userRole.getMenuAuths() && userRole.getMenuAuths().size()>0 ){
				dwz.setMessage("删除失败!<br>错误信息：当前用户角色包含<font color='red'>"+userRole.getMenuAuths().size()+"</font>条角色菜单权限数据！");
				dwz.setStatusCode("300");
				DwzAjaxResult.josnMessage(dwz);
				return;
			}
			
			// ==>2.判断是否包含内部用户信息
			long insideUserCount = sysInsideUserService.countUserByRoleCode(userRole.getUsrCode());
			if(insideUserCount > 0){
				dwz.setMessage("删除失败!<br>错误信息：当前用户角色包含<font color='red'>"+insideUserCount+"</font>条内部用户信息数据！");
				dwz.setStatusCode("300");
				DwzAjaxResult.josnMessage(dwz);
				return;
			}
			
			// ==>3.判断是否包含外部用户信息
			long outsideUserCount = sysOutsideUserService.countUserByRoleCode(userRole.getUsrCode());
			if(outsideUserCount > 0){
				dwz.setMessage("删除失败!<br>错误信息：当前用户角色包含<font color='red'>"+outsideUserCount+"</font>条外部用户信息数据！");
				dwz.setStatusCode("300");
				DwzAjaxResult.josnMessage(dwz);
				return;
			}
			
			sysUserRoleService.delete(model.getUsrId());
			dwz.setMessage("删除成功!");
			dwz.setNavTabId("userRole_list");
			dwz.setStatusCode("200");
			DwzAjaxResult.josnMessage(dwz);
		} catch (Exception e) {
			e.printStackTrace();
			dwz.setMessage("删除失败!<br>错误信息：" + e.getMessage());
			dwz.setStatusCode("300");
			DwzAjaxResult.josnMessage(dwz);
		}
	}

	/** 查看 */
	public String show() {
		return "";
	}
	
	/** 获取角色列表 */
	public String getRoleList(){
		List<SysUserRole> userRoleList = sysUserRoleService.findUserRoleByGroupCode(usgCode);
		ActionContext.getContext().put("userRoleList", userRoleList);
		return "roleJson";
	}
	
	/** 获取角色列表 */
	public void getRoleList2(){
		List<SysUserRole> userRoleList = sysUserRoleService.findUserRoleByGroupCode(usgCode);
		String jsonStr = "";
		if(userRoleList!=null && userRoleList.size()>0){
			jsonStr +="[\"\", \"---请选择---\"]";
			for (int i = 0; i < userRoleList.size(); i++) {
				jsonStr+=",[\""+userRoleList.get(i).getUsrCode()+"\",\""+userRoleList.get(i).getUsrName()+"\"]";
			}
		}else{
			jsonStr +="[\"\", \"---请选择---\"]";
		}
		jsonStr = "[" + jsonStr + "]";
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html");  
		response.setCharacterEncoding("utf-8");
        PrintWriter out = null;  
        try {
			out = response.getWriter();  
			out.println(jsonStr);  
		} catch (IOException e) {
			e.printStackTrace();
		}  
        out.flush();  
		out.close();
	}

	/** 设置权限页面 */
	public String setPrivilegeUI(){
		// ==>1. 准备用户组信息
		List<SysUserGroup> userGroupList = sysUserGroupService.findAll();
		ActionContext.getContext().put("userGroupList", userGroupList);
		
		// ==>2. 准备系统信息
		List<SysDictionary> dictList = sysDictionaryService.getDicListByTypeCode(SOPConfig.DIC_CODE_SYSTEMNAME);
		
		// ==>3. 准备显示数据Map
	/*	Map<String,List<SysMenuAuth>> menuMap = new HashMap<String,List<SysMenuAuth>>();
		for (int i = 0; i < dictList.size(); i++) {
			menuMap.put(dictList.get(i).getDicName(), sysMenuAuthService.findAllMenuListBySys(dictList.get(i).getDicCode(),1));
		}*/
		ActionContext.getContext().put("menuMap", sysMenuAuthService.getMenuTreeMap(dictList, 1)); 
		
		return "setPrivilegeUI";
	}
	
	/** 设置权限 */
	public void setPrivilege(){
		DwzAjaxResult dwz = new DwzAjaxResult();
		try {
			// 从数据库中取出原对象
			SysUserRole userRole = sysUserRoleService.getUserRoleByCode(model.getUsrCode());
			
			// 设置要修改的属性
			List<SysMenuAuth> menuAuths = sysMenuAuthService.getByIds(menuIds.split(","));
			userRole.setMenuAuths(new HashSet<SysMenuAuth>(menuAuths));
			
			// 更新到数据库
			sysUserRoleService.update(userRole);
			
			dwz.setStatusCode("200");
			dwz.setMessage("权限设置成功!");
			dwz.setNavTabId("userRole_setPrivilegeUI");
		} catch (Exception e) {
			e.printStackTrace();
			dwz.setStatusCode("300");
			dwz.setMessage("权限设置失败!<br>错误信息：" + e.getMessage());
		}
		DwzAjaxResult.josnMessage(dwz);
	}
	
	/** 获取权限 */
	public void getPrivilege(){
		if(StringUtils.isNotEmpty(model.getUsrCode())){
			// 准备数据
			SysUserRole userRole = sysUserRoleService.getUserRoleByCode(model.getUsrCode());
			List<SysMenuAuth> menuAuth = new ArrayList<SysMenuAuth>(userRole.getMenuAuths());
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
			JSONArray jsonArray = new JSONArray();
			if(menuAuth!=null && menuAuth.size()>0){
				jsonArray = JSONArray.fromObject(menuAuth, jsonConfig);
			}
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setHeader("Pragma", "No-Cache");
			response.setHeader("Cache-Control", "No-Cache");
			response.setDateHeader("Expires", 0);
			try {
				response.setContentType("text/html");
				response.setCharacterEncoding("utf-8");
				response.getWriter().write(jsonArray.toString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			// 空
		}
		
	}
	
	
	/**安全验证*/
	private void validatePropertitysByAdd(SysUserRole demo)throws Exception{
    	if(!ValidatorUtils.validateUUID(usgId,false)){
    		throw new Exception("属性[用户组编号]输入错误，非法提交！");
    	}
    	/*if(!ValidatorUtils.validateFixedLengthNumber(demo.getSclNumber(), 5, true)){
    		throw new Exception("属性[学校编号]输入错误，非法提交！");
    	}*/
    	if(!ValidatorUtils.validateSafeString(demo.getUsrName(),20, false)){
    		throw new Exception("属性[角色名称]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getUsrDataRange(), 1, false)){
    		throw new Exception("属性[数据权限]输入错误，非法提交！");
    	}
    }
	private void validatePropertitysByUpdate(SysUserRole demo)throws Exception{
		if(!ValidatorUtils.validateUUID(demo.getUsrId(),false)){
    		throw new Exception("属性[角色编号]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateUUID(usgId,false)){
    		throw new Exception("属性[用户组编号]输入错误，非法提交！");
    	}
    	/*if(!ValidatorUtils.validateFixedLengthNumber(demo.getSclNumber(), 5, true)){
    		throw new Exception("属性[学校编号]输入错误，非法提交！");
    	}*/
    	if(!ValidatorUtils.validateSafeString(demo.getUsrName(),20, false)){
    		throw new Exception("属性[角色名称]输入错误，非法提交！");
    	}
    	if(!ValidatorUtils.validateFixedLengthNumber(demo.getUsrDataRange(), 1, true)){
    		throw new Exception("属性[数据权限]输入错误，非法提交！");
    	}
    }
	
	private void validatePropertitysByDel(SysUserRole demo)throws Exception{
		if(!ValidatorUtils.validateUUID(demo.getUsrId(),false)){
    		throw new Exception("属性[角色编号]输入错误，非法提交！");
    	}
    }
	
	public String getUsgId() {
		return usgId;
	}

	public void setUsgId(String usgId) {
		this.usgId = usgId;
	}

	public String getUsgCode() {
		return usgCode;
	}

	public void setUsgCode(String usgCode) {
		this.usgCode = usgCode;
	}

	public String getMenuIds() {
		return menuIds;
	}

	public void setMenuIds(String menuIds) {
		this.menuIds = menuIds;
	}

}
